package accesscontrol;

import java.util.Random;

public class Exercise8 {

	static Connection[] arr1 = new Connection[10];

	public static void main(String[] args) {
		Random r = new Random();
		int l2 = r.nextInt(10) + 1;
		test(l2);
	}

	static void test(int x) {
		Random r = new Random();
		int l3 = 0;
		for (int i = 0; i < 10; i++) {
			if (ConnectionManager.isEmpty) {
				System.out.println("all connections are used");
				System.out.println(ConnectionManager.connectionsStatistic + " connections in history");
				return;
			} else {
				if (i < x)
					arr1[i] = ConnectionManager.getConnection();
				else {
					l3 = r.nextInt(x) + 1;
					for (int j = 0; j < l3; j++) {
						ConnectionManager.releaseConnection(arr1[j]);
						arr1[j] = null;
					}
				}
			}
		}
		 x = r.nextInt(10) + 1;
		 test(x);
	}
}

class ConnectionManager {

	static Connection[] arr = new Connection[10];
	static {
		for (int i = 0; i < arr.length; i++) {
			arr[i] = new Connection();
		}
	}
	static boolean isEmpty = false;
	static int connectionsStatistic = 0;

	public static Connection getConnection() {
		for (int j = 0; j < arr.length; j++) {
			Connection connection = arr[j];
			if (connection != null) {
				arr[j] = null;
				System.out.println("connection " + connection.getId() + " used");
				connectionsStatistic++;
				return connection;
			}
		}
		isEmpty = true;
		System.out.println("no more connection");
		return null;
	}

	public static void releaseConnection(Connection con) {
		if (con == null)
			return;
		arr[con.getId()] = con;
		System.out.println("conneciton " + con.getId() + " released");
		isEmpty = false;
	}
}

class Connection {

	static int counter = 0;
	private int id = counter++;

	public int getId() {
		return id;
	}
}
